<template>
    <div class="add-product-box">
        <el-form :disabled="disabled" ref="form" :model="ruleForm" :rules="rules" label-position="right"
            label-width="120px">
            <el-form-item label="标题" prop="title" :rules="rules.tips">
                <el-input v-model="ruleForm.title" placeholder="请输入" maxlength="50" />
            </el-form-item>
            <el-form-item label="关键词" prop="keywords" :rules="rules.tips">
                <el-input v-model="ruleForm.keywords" type="textarea" placeholder="请输入" maxlength="250" rows="1" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input v-model="ruleForm.description" type="textarea" placeholder="请输入" maxlength="250" rows="2" />
            </el-form-item>
            <el-divider />
            <el-row>
                <el-col :span="16">
                    <el-form-item label="产品名称" prop="product_name" :rules="rules.tips">
                        <el-input v-model="ruleForm.product_name" placeholder="请输入" maxlength="50" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="推荐到首页" prop="hot">
                        <el-switch v-model="ruleForm.hot" active-color="#13ce66" inactive-color="#EEE" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-divider />
            <h2>类目</h2>
            <el-form-item label="一级类目" prop="category1">
                <el-input v-model="ruleForm.category1" placeholder="请输入" maxlength="250" />
            </el-form-item>
            <el-form-item label="二级类目" prop="category2">
                <el-input v-model="ruleForm.category3" placeholder="请输入" maxlength="250" />
            </el-form-item>
            <el-form-item label="三级类目" prop="category3">
                <el-input v-model="ruleForm.category3" placeholder="请输入" maxlength="250" />
            </el-form-item>
            <el-divider />
            <h2 class="flex-space-between align-items-center">
                <span>Banner</span>
                <div>
                    <el-button type="primary" icon="el-icon-plus" @click="addBanner(ruleForm.banner)">添 加</el-button>
                </div>
            </h2>
            <div v-for="(item, bannerIndex) in ruleForm.banner" :key="bannerIndex">
                <div class="banner-box flex-space-between align-items-center">
                    <ProductForm :ref="`bannerForm${bannerIndex}`" v-model="ruleForm.banner[bannerIndex]" class="flex1" />
                    <div>
                        <el-button v-if="bannerIndex > 0" type="danger"
                            @click="delData(ruleForm.banner, bannerIndex)">删除</el-button>
                    </div>
                </div>
            </div>
            <el-divider />
            <h2 class="flex-space-between align-items-center">
                <span>属性</span>
            </h2>
            <div class="flex-space-between align-items-center">
                <el-form-item label="列表样式类型" prop="listType">
                    <Select v-model="ruleForm.listType" :list="lst_listType" :show-all="false" />
                </el-form-item>
                <el-button type="primary" icon="el-icon-plus" @click="addAttr(ruleForm.attributes)">添
                    加</el-button>
            </div>
            <div v-for="(item, attrIndex) in ruleForm.attributes" :key="`attributes${attrIndex}`"
                class="flex-space-between align-items-center">
                <Labelvalue :ref="`attributes${attrIndex}`" v-model="ruleForm.attributes[attrIndex]" class="flex1" />
                <el-button v-show="attrIndex > 0" type="danger" @click="delData(ruleForm.attributes, attrIndex)">
                    删 除
                </el-button>
            </div>
            <el-divider />
            <h2 class="flex-space-between align-items-center">
                <span>详情</span>
            </h2>
            <el-form-item label="描述" prop="detail.des" :rules="rules.tips">
                <el-input v-model="ruleForm.detail.des" type="textarea" placeholder="请输入" maxlength="250" rows="2" />
            </el-form-item>
            <el-divider />
            <h2 class="flex-space-between align-items-center">
                <span>段落</span>
                <el-button type="primary" icon="el-icon-plus" @click="addParagraph">
                    添 加
                </el-button>
            </h2>
            <div v-for="(item, detailIndex) in ruleForm.detail.paragraph" :key="`paragraph${detailIndex}`"
                class="flex-space-between align-items-center banner-box">
                <div class="flex1">
                    <el-form-item label="列表样式类型" :rules="rules.tips">
                        <Select v-model="ruleForm.detail.paragraph[detailIndex].listType" :list="lst_listType"
                            :show-all="false" />
                    </el-form-item>
                    <ParagraphForm :ref="`paragraph${detailIndex}`" v-model="ruleForm.detail.paragraph[detailIndex].banner"
                        class="flex1" />
                    <div v-for="(item, attrIndex) in ruleForm.detail.paragraph[detailIndex].attributes"
                        :key="`paragrapha${detailIndex}${attrIndex}`" class="flex-space-between align-items-center">
                        <Labelvalue :ref="`detailattrs${detailIndex}${attrIndex}`"
                            v-model="ruleForm.detail.paragraph[detailIndex].attributes[attrIndex]" class="flex1" />
                        <div>
                            <el-button v-if="attrIndex === 0" type="primary" icon="el-icon-plus"
                                @click="addAttr(ruleForm.detail.paragraph[detailIndex].attributes)">
                                添 加
                            </el-button>
                            <el-button v-if="attrIndex > 0" type="danger"
                                @click="delData(ruleForm.detail.paragraph[detailIndex].attributes, attrIndex)">
                                删 除
                            </el-button>
                        </div>
                    </div>
                </div>
                <el-button v-if="detailIndex > 0" type="danger" @click="delData(ruleForm.detail.paragraph, detailIndex)">
                    删 除
                </el-button>
            </div>
            <el-divider />
            <h2 class="flex-space-between align-items-center">
                <span>技术</span>
                <el-button type="primary" icon="el-icon-plus" @click="addBanner(ruleForm.technical.process)">
                    添 加
                </el-button>
            </h2>
            <template v-if="ruleForm.technical.process && ruleForm.technical.process.length">
                <div v-for="(item, processIndex) in ruleForm.technical.process" :key="`process${processIndex}`">
                    <div class="banner-box flex-space-between align-items-center">
                        <ProductForm :ref="`processForm${processIndex}`" v-model="ruleForm.technical.process[processIndex]"
                            class="flex1" />
                        <div>
                            <el-button v-if="processIndex > 0" type="danger"
                                @click="delData(ruleForm.technical.process, processIndex)">
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>
            </template>
            <el-divider />
            <h2 class="flex-space-between align-items-center">
                <span>信息</span>
                <el-button type="primary" icon="el-icon-plus" @click="addInformation(ruleForm.technical.information)">
                    添 加
                </el-button>
            </h2>
            <template v-if="ruleForm.technical.information && ruleForm.technical.information.length">
                <div v-for="(item, informationIndex) in ruleForm.technical.information"
                    :key="`information${informationIndex}`">
                    <div class="banner-box flex-space-between align-items-center">
                        <InformationForm :ref="`information${informationIndex}`"
                            v-model="ruleForm.technical.information[informationIndex].content[0]" class="flex1" />
                        <div>
                            <el-button v-if="informationIndex > 0" type="danger"
                                @click="delData(ruleForm.technical.information, informationIndex)">
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>
            </template>
            <el-divider />
            <el-form-item label="质量" prop="quality.category" :rules="rules.select">
                <Select v-model="ruleForm.quality.category" :list="lst_listType" :show-all="false" />
            </el-form-item>
            <el-divider />
            <el-form-item label="包装" prop="packaging.category" :rules="rules.select">
                <Select v-model="ruleForm.packaging.category" :list="lst_listType" :show-all="false" />
            </el-form-item>
        </el-form>
        <el-button v-if="!disabled" type="primary" @click="onSubmit">保 存</el-button>
    </div>
</template>

<script>
import { postProduct, getProduct, editProduct } from '@/api/index'
import ProductForm from '@/views/product/product-form.vue'
import InformationForm from '@/views/product/information-form.vue'
import ParagraphForm from '@/views/product/paragraph-form.vue'
import Labelvalue from '@/views/product/labelvalue.vue'
import Select from '@/components/Select/index.vue'
import FormMixin from "@/views/product/form-mixin.js";
export default {
    name: 'AddDownload',
    mixins: [FormMixin],
    components: { ProductForm, Select, Labelvalue, ParagraphForm, InformationForm },
    data() {
        return {
            type: 1,
            ruleForm: {
                // 是否推荐到首页
                hot: false,
                /** 标题 */
                title: null,
                keywords: null,
                /** 描述 */
                description: null,
                product_name: null,
                category1: null,
                category3: null,
                category2: null,
                banner: [
                    {
                        type: 'img',
                        img: null,
                        title: null,
                        banner: null,
                        des: null,
                        link: null
                    }
                ],
                listType: '.',
                attributes: [
                    {
                        'name': '直径',
                        'value': '0.40-36mm',
                        'isImportant': false
                    }
                ],
                detail: {
                    des: '',
                    paragraph: [
                        {
                            title: '',
                            listType: '.',
                            attributes: [
                                {
                                    name: '',
                                    value: '',
                                    isImportant: false
                                }
                            ],
                            banner: {
                                img: '',
                                link: '',
                                type: 'img',
                                title: ''
                            }
                        }
                    ]
                },
                technical: {
                    process: [
                        {
                            type: 'img',
                            des: '',
                            img: '',
                            banner: '',
                            link: '',
                            title: ''
                        }
                    ],
                    information: [
                        {
                            title: '',
                            content: [
                                {
                                    title: '',
                                    tips: '',
                                    table: '',
                                    des: ''
                                }
                            ]
                        }
                    ]
                },
                quality: {
                    category: '.'
                },
                packaging: {
                    category: '.'
                }
            },
            lst_listType: [
                { label: '中心点', value: '.' },
                { label: '-', value: '-' },
                { label: '序号', value: '）' },
                { label: '无', value: '-' }
            ],
            rules: {
                description: [
                    { 'required': true, 'message': '请输入', 'trigger': 'blur' }
                ],
                tips: [
                    { 'required': true, 'message': '请输入', 'trigger': 'blur' }
                ],
                select: [
                    { 'required': true, 'message': '请选择', 'trigger': 'change' }
                ]
            },
            id: null
        }
    },
    async created() {
        this.type = Number(this.$route.query.type) || 1
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            let res = await getProduct({ id: this.$route.query.id })
            this.ruleForm = JSON.parse(res.data.content)
        }
    },
    methods: {
        async onSubmit() {
            try {
                // 验证页面基础信息
                await this.$refs.form.validate()
                // 验证banner
                const bannersValidates = this.ruleForm.banner.map((item, index) => this.$refs[`bannerForm${index}`][0].validate())
                await Promise.all(bannersValidates)
                // 验证属性
                const attributesValidates = this.ruleForm.attributes.map((item, index) => this.$refs[`attributes${index}`][0].validate())
                await Promise.all(attributesValidates)
                // 验证 详情内容
                const detailParagraphValidates = this.ruleForm.detail.paragraph.map((item, index) => this.$refs[`paragraph${index}`][0].validate())
                await Promise.all(detailParagraphValidates)
                // 验证 详情label value
                const detailAttrsValidates = []
                this.ruleForm.detail.paragraph.forEach((item, index) => {
                    item.attributes.forEach((attr, attrIndex) => {
                        detailAttrsValidates.push(this.$refs[`detailattrs${index}${attrIndex}`][0].validate())
                    })
                })
                await Promise.all(detailAttrsValidates)
                // 验证 技术
                const processValidates = this.ruleForm.technical.process.map((item, index) => this.$refs[`processForm${index}`][0].validate())
                await Promise.all(processValidates)
                // 验证 信息
                const informationValidates = this.ruleForm.technical.information.map((item, index) => this.$refs[`information${index}`][0].validate())
                await Promise.all(informationValidates)
                let formData = new FormData()
                !this.id && formData.append('type', this.type)
                this.id && formData.append('id', this.id)
                formData.append('content', JSON.stringify(this.ruleForm))
                let fetchApi = this.id ? editProduct : postProduct
                await fetchApi(formData)
                this.$message({
                    type: 'success',
                    message: '成功'
                })
                !this.id && this.$router.push('/product')
            } catch (error) {
                console.log('error', error)
            }
        },
        addInformation(data) {
            data.push({
                title: '',
                content: [
                    {
                        title: '',
                        tips: '',
                        table: '',
                        des: ''
                    }
                ]
            })
        },
        addParagraph() {
            this.ruleForm.detail.paragraph.push({
                title: '',
                listType: '.',
                attributes: [
                    {
                        name: '',
                        value: '',
                        isImportant: false
                    }
                ],
                banner: {
                    img: '',
                    link: '',
                    type: 'img',
                    title: ''
                }
            })
        },
        addAttr(data) {
            data.push({
                name: '', value: '', isImportant: false
            })
        },
        addBanner(data) {
            data.push({
                type: 'img',
                img: null,
                title: null,
                banner: null,
                des: null,
                link: null
            })
        },
        async delData(data, index, tips) {
            await this.$confirm(`此操作将删除${tips || '数据'}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            data.splice(index, 1)
        }
    }
}
</script>
<style lang="scss">
.add-product-box {
    padding: 10px;

    .banner-box {
        border: 1px solid #ebeef5;
        margin-bottom: 10px;
        padding: 5px;
    }
}
</style>
